package com.sfh.gd.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.sfh.gd.common.enums.DeviceType;
import com.sfh.gd.domain.entity.MemberDO;
import com.sfh.gd.domain.dto.LoginWxDTO;
import com.sfh.gd.domain.dto.SignInDTO;
import com.sfh.gd.domain.entity.SysUseDO;
import com.sfh.gd.mapper.MemberMapper;
import com.sfh.gd.mapper.SysUserMapper;
import com.sfh.gd.service.MemberService;
import com.sfh.gd.util.StpKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class MemberServiceImpl  extends ServiceImpl<MemberMapper, MemberDO>  implements MemberService {


    private final WxMaService wxMaService;
    private final MemberMapper memberMapper;

    @Transactional
    @Override
    public SaResult login(LoginWxDTO loginVo) {
        if (StringUtils.isBlank(loginVo.getCode())) {
            return SaResult.error("appid不能为空！");
        }

        if (!wxMaService.switchover(loginVo.getAppid())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", loginVo.getAppid()));
        }
        WxMaJscode2SessionResult session;

        Map map = new HashMap();
        try {
            session = wxMaService.getUserService().getSessionInfo(loginVo.getCode());
            // 根据 OpenId 获取用户信息，如果用户不存在责进行注册
            MemberDO member = memberMapper.selectOneByQuery(new QueryWrapper().eq(MemberDO::getOpenid, session.getOpenid()));
            if (ObjectUtil.isNotNull(member)) {
                if ("1".equals(member.getStatus())) {
                    return SaResult.error("用户已禁用");
                }
                if ("2".equals(member.getDelFlag())) {
                    return SaResult.error("用户已删除");
                }
                StpKit.USER.login(member.getId(), DeviceType.WECHAT.getName());
                SaTokenInfo tokenInfo = StpKit.USER.getTokenInfo();
                map.put("tokenInfo", tokenInfo.getTokenValue());
                return SaResult.data(map);
            } else {
                map.put("openId", session.getOpenid());
                return SaResult.data(map);
            }
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return SaResult.error();
    }

    @Override
    public SaResult signIn(SignInDTO signInDTO) {
        // 注册新用户
        MemberDO member = new MemberDO();
        member.setOpenid(signInDTO.getOpenId());
        member.setNickName("用户" + signInDTO.getPhoneNum().substring(7, 11));
        member.setPhoneNum(signInDTO.getPhoneNum());
        member.setCreateTime(LocalDateTime.now());
        member.setStatus("0");
        member.setDelFlag("0");
        memberMapper.insert(member);
        StpKit.USER.login(member.getId(), DeviceType.WECHAT.getName());
        StpKit.USER.getSession().set(member.getId().toString(), member);
        SaTokenInfo tokenInfo = StpKit.USER.getTokenInfo();

        return SaResult.data(tokenInfo);
    }

    @Override
    public SaResult getUserInfo() {
        long memberId = StpKit.USER.getLoginIdAsLong();
        MemberDO memberDO = memberMapper.selectOneByQuery(new QueryWrapper().eq("id", memberId));
        return SaResult.data(memberDO);
    }
}
